package com.click.service;

import com.click.common.BusinessException;
import com.click.common.ErrorCode;
import com.click.dto.WxLoginDTO;
import com.click.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WxAuthService {
    
    @Value("${wx.miniapp.appid}")
    private String appid;
    
    @Value("${wx.miniapp.secret}")
    private String secret;
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    /**
     * 微信登录
     */
    public Map<String, Object> wxLogin(WxLoginDTO wxLoginDTO) {
        // 1. 获取微信session
        Map<String, String> session = getWxSession(wxLoginDTO.getCode());
        
        String openid = session.get("openid");
        String sessionKey = session.get("session_key");
        
        // 2. 查询或创建用户
        User user = findOrCreateUser(openid, wxLoginDTO);
        
        // 3. 生成token（简化版，实际应该用JWT）
        String token = generateToken(user.getId(), openid);
        
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userInfo", user);
        result.put("sessionKey", sessionKey);
        
        return result;
    }
    
    /**
     * 获取微信session
     */
    private Map<String, String> getWxSession(String code) {
        String url = String.format(
            "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
            appid, secret, code
        );
        
        try {
            @SuppressWarnings("unchecked")
            ResponseEntity<Map<String, Object>> response = restTemplate.getForEntity(url, (Class<Map<String, Object>>) (Class<?>) Map.class);
            Map<String, Object> responseBody = response.getBody();
            
            if (responseBody == null || responseBody.containsKey("errcode")) {
                log.error("微信登录失败: {}", responseBody);
                String errmsg = responseBody != null ? String.valueOf(responseBody.get("errmsg")) : "未知错误";
                throw new BusinessException(ErrorCode.WX_LOGIN_FAILED, "微信登录失败: " + errmsg);
            }
            
            Map<String, String> session = new HashMap<>();
            session.put("openid", (String) responseBody.get("openid"));
            session.put("session_key", (String) responseBody.get("session_key"));
            session.put("unionid", (String) responseBody.get("unionid"));
            
            return session;
        } catch (Exception e) {
            log.error("调用微信接口失败: {}", e.getMessage(), e);
            throw new BusinessException(ErrorCode.WX_LOGIN_FAILED, "微信服务异常");
        }
    }
    
    /**
     * 查询或创建用户
     */
    private User findOrCreateUser(String openid, WxLoginDTO wxLoginDTO) {
        // 模拟用户创建逻辑 - 将在M2数据库设计中实现真实逻辑
        User user = new User();
        user.setId(1L);
        user.setOpenid(openid);
        user.setNickname("微信用户");
        user.setAvatarUrl("");
        
        return user;
    }
    
    /**
     * 生成token（简化版）
     */
    private String generateToken(Long userId, String openid) {
        // 模拟token生成 - 将在M3安全模块中实现JWT
        return "mock_token_" + userId + "_" + openid;
    }
}